package com.tg.service.flow;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.tg.service.Application;
import com.tg.service.flow.ui.superFlow.SpFlow;
import com.tg.service.flow.flow.FlowNode;
import com.tg.service.flow.flow.SpringFlowEngine;
import com.tg.service.flow.ui.superFlow.SpFlowNode;
import com.tg.service.flow.ui.superFlow.SpFlowNodeMeta;
import com.tg.service.utils.ContextUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@SpringBootApplication
public class EngineTest {

    public static SpFlow OUT_DTO = null;

    private static ConfigurableApplicationContext context;

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
        context = ctx;
        ContextUtil.setApplicationContext(ctx);
    }

    @RequestMapping(value = "/flow/ask")
    public String ask(String req) {
        JSONObject reqJson = JSONObject.parseObject(req);

//        SpringFlowEngine.build(this.generateNodes(), EngineTest.context).run(reqJson);
        List<SpFlowNodeMeta> nodes = EngineTest.OUT_DTO.getNodes()
                .stream().map(SpFlowNode::getMeta).collect(Collectors.toList());
        SpringFlowEngine.build(nodes, EngineTest.context).run(reqJson);

        return "done";
    }

    private List<FlowNode> generateNodes() {
        ArrayList<FlowNode> nodes = Lists.newArrayList();

        FlowNode node1 = new FlowNode();
        node1.setBeFirst(true);
        node1.setBeLast(false);
        node1.setId("1");
        node1.setKey("metaRule1");
        node1.setNextIds(Lists.newArrayList("2"));
        node1.setCondition(null);

        FlowNode node2 = new FlowNode();
        node2.setBeFirst(false);
        node2.setBeLast(false);
        node2.setId("2");
        node2.setKey("metaRule2");
        node2.setNextIds(null);
        node2.setCondition("#tuple.req.getInteger('age')>20");

        nodes.add(node1);
        nodes.add(node2);
        return nodes;
    }
}
